package com.ala4.oxcafe.boot.filter;

import com.ala4.oxcafe.boot.request.RepeatReadHttpRequest;
import com.ala4.oxcafe.constants.SecurityConstants;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;

import java.io.IOException;

/**
 * 可重复读读取流
 *
 * @author PING
 * @version 1.0
 * @date 2025/2/18 15:16
 */
@Slf4j
@Order(Integer.MIN_VALUE)
@WebFilter(urlPatterns = "/*")
public class CachingContentFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        if (request instanceof HttpServletRequest httpServletRequest) {
            httpServletRequest.setCharacterEncoding(SecurityConstants.CHARACTER_ENCODING_UTF_8);
            HttpServletRequest requestWrapper = new RepeatReadHttpRequest(httpServletRequest);
            if (contentType != null && request.getContentType().equals(MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
                chain.doFilter(request, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }

}
